package aorey.nosql;

import java.io.File;
import java.util.List;
import net.sf.ehcache.Cache;
import net.sf.ehcache.CacheManager;
import net.sf.ehcache.Element;

public class EhcacheUtil {

    // 缓存对象
    private CacheManager manager;
    // 节点缓存对象
    private Cache cache;
    // 导出对象
    private static EhcacheUtil ehCache;

    /**
     * 缓存初始化
     *
     * @param path 配置文件路径
     */
    public EhcacheUtil(String path) {

        CacheManager.getInstance().shutdown(); 
        File config_file = new File(path);
        if (config_file.exists())
        {
            this.manager = CacheManager.create(path); 
        }

    }

    /**
     * 获取缓存对象
     *
     * @param path 配置文件路径
     * @return
     */
    public static EhcacheUtil getInstance(String path) {
        if (ehCache == null) {
            ehCache = new EhcacheUtil(path);
        }
        return ehCache;
    }

    /**
     * 设置带超时的缓存
     *
     * @param cacheName 缓存区域
     * @param key 缓存键
     * @param value 缓存值
     * @param writeTime	闲置时间
     * @param timeOut 缓存超时
     */
    public void put(String cacheName, String key, Object value, int writeTime, int timeOut) {
        Cache cache = this.manager.getCache(cacheName);
        Element element = new Element(key, value, false, writeTime, timeOut);
        cache.put(element);
    }

    /**
     * 设置长期缓存
     *
     * @param cacheName	缓存区域
     * @param key 缓存键
     * @param value 缓存值
     */
    public void put(String cacheName, String key, Object value) {
        Cache cache = this.manager.getCache(cacheName);
        Element element = new Element(key, value);
        cache.put(element);
    }

    /**
     * 获取缓存对象
     *
     * @param cacheName 缓存区域
     * @param key 缓存键
     * @return 缓存值
     */
    public Object get(String cacheName, String key) {
        Cache cache = manager.getCache(cacheName);
        Element element = cache.get(key);
//	        System.out.println(element.getCreationTime());
        return element == null ? null : element.getObjectValue();
    }

    /**
     * 刷新缓存
     *
     * @param cacheName 缓存区间
     */
    public void flush(String cacheName) {
        Cache cache = this.manager.getCache(cacheName);
        cache.flush();
    }

    /**
     * 获取还粗你对象
     *
     * @param cacheName 缓存
     * @return 缓存对象
     */
    public Cache get(String cacheName) {
        return manager.getCache(cacheName);
    }

    /**
     * 删除缓存键
     *
     * @param cacheName	存储区
     * @param key 删除键
     */
    public void remove(String cacheName, String key) {
        Cache cache = manager.getCache(cacheName);
        cache.remove(key);
    }

    /**
     * 获取指定存储节点的key
     * @param cacheName
     * @return 
     */
    public List<String> getKeys(String cacheName)
    {
        return manager.getCache(cacheName).getKeys();
    }
    
    
    /**
     * 关闭缓存服务器
     */
    public void close() {
        this.manager.shutdown();
    }
}
